import React, { Profiler, useState, useRef } from "react";
import { useEffect } from "react";
import create from "zustand";
import shallow from "zustand/shallow";

const useCountStore = create((set, get) => ({
  count: 0,
  other: "other",
  add: () => set((store) => ({ count: store.count + 1 })),
}));
let rerenderCount = 0;
function Component1({ out }) {
  const { count, other, add } = useCountStore((store) => ({
    count: store.count,
    other: store.other,
    add: store.add,
  }));

  return (
    <>
      <ul>
        <li>rerenderCount: {++rerenderCount}</li>
        <li>
          store.count: {count} <br />{" "}
          <button onClick={add}>add store.count</button>{" "}
        </li>
        <li>store.other: {other}</li>
      </ul>
    </>
  );
}
let rerenderCount2 = 0;
function Component2() {
  const { count } = useCountStore((store) => ({
    count: store.count,
  }));
  return (
    <>
      <ul>
        <li>rerenderCount: {++rerenderCount2}</li>
        <li>
          store.count: {count} <br />
        </li>
      </ul>
    </>
  );
}

let rerenderCount3 = 0;
let oldStore;
function Component3() {
  const store = useCountStore((store) => store);
  useEffect(() => {
    oldStore = store;
  });
  return (
    <>
      <ul>
        <li>rerenderCount: {++rerenderCount3}</li>
        <li>
          是否 store 和 oldStore 相等 : {store === oldStore ? "相等" : "不相等"}
          <br />
        </li>
        <li>{JSON.stringify(store)}</li>
        <li>{JSON.stringify(oldStore)}</li>
      </ul>
    </>
  );
}

let rerenderCount4 = 0;
function Component4() {
  // const other = useCountStore((store) => store.other);
  const { other } = useCountStore((store) => ({
    other: store.other,
  }));

  return (
    <>
      <ul>
        <li>rerenderCount: {++rerenderCount4}</li>
        <li>
          store.other: {other} <br />
        </li>
      </ul>
    </>
  );
}

let rerenderCount5 = 0;
function Component5() {
  // const other = useCountStore((store) => store.other);
  const { other } = useCountStore(
    (store) => ({
      other: store.other,
    }),
    shallow
  );

  return (
    <>
      <ul>
        <li>rerenderCount: {++rerenderCount5}</li>
        <li>
          store.other: {other} <br />
        </li>
      </ul>
    </>
  );
}

function App() {
  const onRender = (...props) => {
    console.log("onRender", props);
  };
  return (
    <Profiler id="App" onRender={onRender}>
      <div>
        <h1>Component1</h1>
        <Component1 />

        <h1>Component2</h1>
        <Component2 />

        <h1>Component3</h1>
        <Component3 />

        <h1>Component4</h1>
        <Component4 />

        <h1>Component5</h1>
        <Component5 />
      </div>
    </Profiler>
  );
}

export default App;
